<?php

class System_Models_Listtype extends Zend_Db_Table_Abstract {

    protected $_name = "listtype";
    protected $_primary = "ListtypeID";
    protected $_primary_name;
    public function __construct()
    {
        parent::__construct();
        $this->_primary_name = $this->_primary;
    }

    public function getAllListtype($params) {

        $pagenum = $params['pagenum'];
        $pagesize = $params['pagesize'];
        $start = $pagenum * $pagesize;

        $where = '1=1';
        // Filter
        if (isset($params['filterscount']))
        {
            $filterscount = $params['filterscount'];
            
            if ($filterscount > 0)
            {
                $where .= " And (";
                $tmpdatafield = "";
                $tmpfilteroperator = "";
                for ($i=0; $i < $filterscount; $i++)
                {
                    // get the filter's value.
                    $filtervalue = $params["filtervalue" . $i];
                    // get the filter's condition.
                    $filtercondition = $params["filtercondition" . $i];
                    // get the filter's column.
                    $filterdatafield = $params["filterdatafield" . $i];
                    // get the filter's operator.
                    $filteroperator = $params["filteroperator" . $i];
                    
                    if ($tmpdatafield == "")
                    {
                        $tmpdatafield = $filterdatafield;           
                    }
                    else if ($tmpdatafield <> $filterdatafield)
                    {
                        $where .= ")AND(";
                    }
                    else if ($tmpdatafield == $filterdatafield)
                    {
                        if ($tmpfilteroperator == 0)
                        {
                            $where .= " AND ";
                        }
                        else $where .= " OR ";  
                    }
                    
                    // build the "WHERE" clause depending on the filter's condition, value and datafield.
                    $where .= Clound_Public::getInstance()->getClauseByFilter($filtercondition, $filterdatafield, $filtervalue);
                                    
                    if ($i == $filterscount - 1)    $where .= ")";

                    $tmpfilteroperator = $filteroperator;
                    $tmpdatafield = $filterdatafield;           
                }
                
            }
        }
        // Sort
        $orders =' Orders ASC';
        if (isset($params['sortdatafield'])) {
            $sortfield = $params['sortdatafield'];
            $sortorder = $params['sortorder'];
            if ($sortorder != '') {
                if ($sortorder == "desc") {
                    $orders = " " . $sortfield . " DESC";
                } else if ($sortorder == "asc") {
                    $orders = " " . $sortfield . " ASC";
                }
            }
        }

        // Lay tong
        try {
            $getTotal = $this->select()->from($this, array())->columns(array('total' => new Zend_Db_Expr('COUNT(*)')))->where($where);
            $rows = $this->getAdapter()->fetchRow($getTotal);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        $total_rows = $rows['total'];
        // Lay du lieu
        try {
            $query = $this->select()->from($this)->where($where)->order($orders)->limit($pagesize, $start);
            $rows = $this->getAdapter()->fetchAll($query);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        $data[] = array(
            'TotalRows' => $total_rows,
            'Rows' => $rows
        );

        return $data;
    }

    public function selectRow($id){
        if($id){
            $query = $this->select()->from($this)->where('ListtypeID = ?', $id);
            try {
                $rows = $this->getAdapter()->fetchRow($query);
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }else{
            $query = $this->select()->from($this, '')->columns(array('Orders' => new Zend_Db_Expr('MAX(Orders)')));
            $orders = $this->getAdapter()->fetchRow($query);
            $rows = array('ListtypeID'=>''
                            ,'Code'=>''
                            ,'Name'=>''
                            ,'Orders'=>$orders['Orders']+1
                            ,'Status'=>'1'
                            ,'ListtypeID'=>''
                        );
        }
        return $rows;
    }
    public function deleteRows($listId){

        $aListtypeID = explode(',', $listId);
        $query = "SELECT count(*) As TotalRows FROM $this->_name A";
        $query .= " Join list B On A.$this->_primary_name = B.$this->_primary_name";
        $query .= " Where ".$this->getAdapter()->quoteInto("A.$this->_primary_name IN (?)", $aListtypeID);
        try {
            $rows = $this->getAdapter()->fetchRow($query);
        } catch (Exception $e) {
            echo $e->getMessage();
        }

        if($rows['TotalRows']>0){
            $aResult = array('errors'=>1
                            ,'mgs'=>'Loại danh mục này có dữ liệu, bạn cần phải xóa trong danh mục đối tượng trước!');
        }else{
            $where = $this->getAdapter()->quoteInto("$this->_primary_name IN (?)", $aListtypeID);
            try {
                $aResult = array('errors'=>!$this->delete($where)
                    ,'mgs'=>$where
                    );
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }
        return $aResult;
    }
    
    public function isValid($data) {       
        $where = " Where ".$this->getAdapter()->quoteInto("$this->_primary_name <> ?", $data[$this->_primary_name])
                .$this->getAdapter()->quoteInto(" And Code = ?",$data['Code']);
        try {
            $rows = $this->getAdapter()->fetchRow("SELECT COUNT(*) as total FROM $this->_name ".$where);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        if($rows['total']){
            return false;
        }else{
            return true;
        }
        return $rows['total'];
    }    

    public function getlist(){
        $query = $this->select()->from($this,$this->_primary_name)->columns(array('Name'));
        $rows = $this->getAdapter()->fetchAll($query);
        return $rows;
    }
    public function getFileXmL($id){
        $query = $this->select()->from($this,'')->columns(array('XmlFileName'))->where('ListtypeID = ?', $id);
        $rows = $this->getAdapter()->fetchRow($query);
        return $rows['XmlFileName'];
    }
    
    public function reOrder($iListtypeID,$iOrder){
         $where = " Where ".$this->getAdapter()->quoteInto("$this->_primary_name <> ?", $iListtypeID)
                    .$this->getAdapter()->quoteInto(" And Orders >= ?",$iOrder);
        
        $rows = $this->getAdapter()->fetchAll("SELECT $this->_primary_name,Orders FROM $this->_name ".$where." Order by Orders");
        if($rows){
            foreach ($rows as $key => $value) {
                $id = $value[$this->_primary_name];
                try {
                    $this->update(array('Orders'=> $iOrder+1+$key),"$this->_primary_name = $id");
                } catch (Exception $e) {
                    echo $e->getMessage();
                }
            }
        }
        return $rows;

    }
    public function getAll($aListtypeID,$iStatus){
        
        $query = "SELECT A.Code As ListTypeCode,B.* FROM $this->_name A";
        $query .= " Inner Join list B On A.$this->_primary_name = B.$this->_primary_name";
        $query .= " Where ".$this->getAdapter()->quoteInto("B.Status = ?",$iStatus);
        if ($aListtypeID) {
            $query .= $this->getAdapter()->quoteInto(" And A.$this->_primary_name IN (?)", $aListtypeID);
        }
        $query .= " Order by A.Code,B.Orders";
		//echo $query;exit;
        $rows = $this->getAdapter()->fetchAll($query);
        return $rows;
    }
}
